/**
* @Auther:gy
* @Date:2021/10/19 15:46
 */

package datasource

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"gitee.com/yanggit123/tool/module"
	"github.com/go-sql-driver/mysql"
	"io/ioutil"
	"time"
)

func mysqlSSL(conf module.MysqlConf) error {
	rootCertPool := x509.NewCertPool()
	pem, err := ioutil.ReadFile(conf.Certs[0])
	if err != nil {
		return err
	}
	if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
		return errors.New("Failed to append PEM.")
	}
	clientCert := make([]tls.Certificate, 0, 1)
	certs, err := tls.LoadX509KeyPair(conf.Certs[1], conf.Certs[2])
	if err != nil {
		return err
	}
	clientCert = append(clientCert, certs)
	err = mysql.RegisterTLSConfig("custom", &tls.Config{
		RootCAs:      rootCertPool,
		Certificates: clientCert,
	})
	return err
}
func getMysqlDsn(conf module.MysqlConf) (string, error) {
	cfg := mysql.Config{
		User:                 conf.Username,
		Passwd:               conf.Password,
		Addr:                 conf.Address, //IP:PORT
		Net:                  "tcp",
		DBName:               conf.DbName,
		Loc:                  time.Local,
		AllowNativePasswords: true,
		Params: map[string]string{
			"charset":   "utf8mb4",
			"parseTime": "True",
			"loc":       "Local",
		},
		TLSConfig: conf.TLSConfig,
	}

	if len(conf.Certs) == 3 && cfg.TLSConfig == "" {
		err := mysqlSSL(conf)
		if err != nil {
			return "", err
		}
		cfg.TLSConfig = "custom"
	}
	return cfg.FormatDSN(), nil
}
